package com.xingkeduo.service.hairdresser.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xingkeduo.dao.TMarketingCouponBagMapper;
import com.xingkeduo.dao.TMarketingRelevantMapper;
import com.xingkeduo.model.example.TMarketingCouponBagExample;
import com.xingkeduo.model.example.TMarketingRelevantExample;
import com.xingkeduo.model.param.MarketingParam.MarketingStatusEnum;
import com.xingkeduo.model.param.MarketingParam.MarketingTypeEnum;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam;
import com.xingkeduo.model.param.MarketingReceiveHistoryParam.MarketingReceiveSendTypeEnum;
import com.xingkeduo.model.po.TMarketing;
import com.xingkeduo.model.po.TMarketingCouponBag;
import com.xingkeduo.model.po.TMarketingRelevant;
import com.xingkeduo.model.vo.MarketingResponseVo;
import com.xingkeduo.service.api.marketing.ReceiveService;
import com.xingkeduo.service.base.MarketingService;
import com.xingkeduo.service.hairdresser.HairdresserService;
import com.xingkeduo.util.Constant;
import com.xingkeduo.util.DateUtils;
import com.xingkeduo.util.tool.ResponseMessage;

@Service
public class HairdresserServiceImpl implements HairdresserService {
	Logger logger = LoggerFactory.getLogger(HairdresserServiceImpl.class);
	@Autowired
	TMarketingCouponBagMapper tMarketingCouponBagMapper;
	@Autowired
	TMarketingRelevantMapper tMarketingRelevantMapper;
	@Autowired
	MarketingService marketingService;
	@Autowired
	ReceiveService receiveService;

	@Override
	public ResponseMessage getMarketingSellListByStoreId(Long storeId) {
		List<TMarketingCouponBag> couponBagList = new ArrayList<TMarketingCouponBag>();
		// 查询设置部分门店的售卖中是否包含本门店
		TMarketingCouponBagExample someCouponBagExample = new TMarketingCouponBagExample();
		someCouponBagExample.createCriteria().andStatusEqualTo(MarketingStatusEnum.UP.getCode())
				.andSellEnableEqualTo(Constant.STATUS_YES)
				.andSellStoreIdsLike("%" + storeId + "%");
		List<TMarketingCouponBag> someCouponBagList = tMarketingCouponBagMapper.selectByExample(someCouponBagExample);
		if (!CollectionUtils.isEmpty(someCouponBagList)) {
			couponBagList.addAll(someCouponBagList);
		}
		// 查询设置全门店的售卖中是否包含本门店
		TMarketingCouponBagExample allCouponBagExample = new TMarketingCouponBagExample();
		allCouponBagExample.createCriteria().andStatusEqualTo(MarketingStatusEnum.UP.getCode()).andSellEnableEqualTo(Constant.STATUS_YES).andStoreIdsEqualTo("0");
		List<TMarketingCouponBag> allCouponBagList = tMarketingCouponBagMapper.selectByExample(allCouponBagExample);
		// 本店下所有的优惠
		if (!CollectionUtils.isEmpty(allCouponBagList)) {
			couponBagList.addAll(allCouponBagList);
		}
		// 返回券包数据
		List<Map<String, String>> resultList = allCouponBagList.stream().map(this::convertSellListResponse)
				.collect(Collectors.toList());
		return ResponseMessage.ok(resultList);
	}

	public Map<String, String> convertSellListResponse(TMarketing marketing) {
		Map<String, String> returnMap = new HashMap();
		returnMap.put("id", marketing.getId().toString());// 优惠包id
		returnMap.put("marketingType", marketing.getMarketingType().toString());// 优惠包类型
		returnMap.put("marketingName", marketing.getName());// 优惠包名称
		returnMap.put("sellPrice", marketing.getSellPrice().toString());
		int couponCount = 0;
		int cardCount = 0;
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			// 查询优惠包下的券
			TMarketingRelevantExample couponExample = new TMarketingRelevantExample();
			couponExample.createCriteria().andMarketingIdEqualTo(marketing.getId())
					.andMarketingTypeEqualTo(MarketingTypeEnum.COUPON.getCode()).andStatusEqualTo(Constant.STATUS_YES)
					.andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> couponList = tMarketingRelevantMapper.selectByExample(couponExample);
			if (!CollectionUtils.isEmpty(couponList)) {
				for (TMarketingRelevant relevant : couponList) {
					couponCount = couponCount + relevant.getTotalQuantity();
				}
			}
			// 查询优惠包下的卡
			TMarketingRelevantExample cardExample = new TMarketingRelevantExample();
			cardExample.createCriteria().andMarketingIdEqualTo(marketing.getId())
					.andMarketingTypeEqualTo(MarketingTypeEnum.CARD.getCode()).andStatusEqualTo(Constant.STATUS_YES)
					.andTotalQuantityGreaterThan(0);
			List<TMarketingRelevant> cardList = tMarketingRelevantMapper.selectByExample(cardExample);
			if (!CollectionUtils.isEmpty(cardList)) {
				for (TMarketingRelevant relevant : cardList) {
					cardCount = cardCount + relevant.getTotalQuantity();
				}
			}
		}
		returnMap.put("couponCount", couponCount + "");// 券数量
		returnMap.put("cardCount", cardCount + "");// 卡数量
		return returnMap;
	}

	@Override
	public ResponseMessage getMarketingDetail(Long marketingId, Integer marketingType) {
		// 券包信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingId,
				marketingType);
		// 领取规则验证
		return marketingRuleReceiveValidation(null, marketing);
	}
	
	private ResponseMessage marketingRuleReceiveValidation(Long userId, TMarketing marketing) {
		if (marketing == null) {
			return ResponseMessage.error("未查询到优惠包信息", 500);
		}
		if (marketing.getMarketingType().intValue() != MarketingTypeEnum.COUPON_BAG.getCode()) {
			return ResponseMessage.error("当前售卖只支持优惠包",500);
		}
		if (marketing.getSellEnable().intValue()!=Constant.STATUS_YES) {
			return ResponseMessage.error("当前优惠包不可售卖",500);
		}
		if (marketing.getStockQuantity().intValue() != 0 && marketing.getSurplusQuantity().intValue() <= 0) {
			return ResponseMessage.error("优惠包库存不足", 500);
		}
		if (marketing.getReceiveStartTime().after(new Date())) {
			return ResponseMessage.error("优惠包尚未开始售卖,开始时间"
					+ DateUtils.formatDate(marketing.getReceiveStartTime(), DateUtils.DATE_FORMAT), 500);
		}
		if (marketing.getReceiveEndTime().before(new Date())) {
			return ResponseMessage.error("优惠包尚已截止售卖", 500);
		}

		if (MarketingStatusEnum.UP.getCode() != marketing.getStatus().intValue()) {
			return ResponseMessage.error("优惠包已下架", 500);
		}
		int couponCount=0;
		int cardCount=0;
		List<TMarketingRelevant> historyList = null;
		// 券包情况下，需额外验证卡券是否上架
		if (marketing.getMarketingType().intValue() == MarketingTypeEnum.COUPON_BAG.getCode()) {
			TMarketingRelevantExample tMarketingRelevantExample = new TMarketingRelevantExample();
			tMarketingRelevantExample.createCriteria()
									 .andMarketingIdEqualTo(marketing.getId())
									 .andStatusEqualTo(Constant.STATUS_YES)
									 .andTotalQuantityGreaterThan(0);
			tMarketingRelevantExample.setOrderByClause("marketing_type asc");
			historyList = tMarketingRelevantMapper.selectByExample(tMarketingRelevantExample);
			if (CollectionUtils.isEmpty(historyList)) {
				return ResponseMessage.error("优惠包中没有有效的优惠券，卡", 500);
			}
			for (TMarketingRelevant relevant : historyList) {
				TMarketing oldmarketing = marketingService.selectMarketingByPrimaryKey(relevant.getSupportBusinessId(),
						relevant.getMarketingType());
				if (oldmarketing == null) {
					return ResponseMessage.error("优惠包中部分优惠券,卡已下架", 500);
				}
				if (MarketingStatusEnum.UP.getCode() != oldmarketing.getStatus().intValue()) {
					return ResponseMessage.error("优惠包中部分优惠券,卡已下架", 500);
				}
				if(relevant.getMarketingType().intValue()==MarketingTypeEnum.COUPON.getCode()) {
					couponCount=couponCount+relevant.getTotalQuantity();
				}
				if(relevant.getMarketingType().intValue()==MarketingTypeEnum.CARD.getCode()) {
					cardCount=cardCount+relevant.getTotalQuantity();
				}
				if (oldmarketing.getUseType() == 0) {// 相对时间
					relevant.setRemark("有效期领取后"+(oldmarketing.getUsePeriod()==null?0:oldmarketing.getUsePeriod())+"天可用");
				}
				if (oldmarketing.getUseType() == 1) {// 指定时间
					relevant.setRemark("有效期至"+(oldmarketing.getUseEndTime()==null?DateUtils.getDate():DateUtils.formatDate(oldmarketing.getUseEndTime(),DateUtils.DATE_FORMAT)));
				}
			}
		}
		MarketingResponseVo marketingResponseVO = new MarketingResponseVo();
		BeanUtils.copyProperties(marketing, marketingResponseVO);
		marketingResponseVO.setCouponCount(couponCount);
		marketingResponseVO.setCardCount(cardCount);
		marketingResponseVO.setMarketingRelevants(historyList);
		return ResponseMessage.ok(marketingResponseVO);
	}

	@Override
	public ResponseMessage bindBagReceiveAccount(Long marketingId, Integer marketingType, Long userId) {
		// 券包信息
		TMarketing marketing = marketingService.selectMarketingByPrimaryKey(marketingId,
				marketingType);
		if (marketing == null) {
			return ResponseMessage.error("未查询到优惠包信息", 500);
		}
		if (marketing.getMarketingType().intValue() != MarketingTypeEnum.COUPON_BAG.getCode()) {
			return ResponseMessage.error("当前售卖只支持优惠包",500);
		}
		MarketingReceiveHistoryParam marketingReceiveHistoryParam = new MarketingReceiveHistoryParam();
		marketingReceiveHistoryParam.setId(marketingId);
		marketingReceiveHistoryParam.setUserId(userId);
		marketingReceiveHistoryParam.setCreateBy(userId);
		marketingReceiveHistoryParam.setSendType(MarketingReceiveSendTypeEnum.HAIRDRESSER_SELL.getCode());
		marketingReceiveHistoryParam.setMarketingType(marketingType);
		marketingReceiveHistoryParam.setCheckFlag(Boolean.FALSE);
		return receiveService.bindBagReceiveAccount(marketingReceiveHistoryParam);
	}

}
